package com.yanqu.road.web.controller.game;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.platform.PlatformDeductIngotsOrder;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.recharge.RechargeOrder;
import com.yanqu.road.entity.recharge.ThirdPartyRechargeOrder;
import com.yanqu.road.entity.web.HttpJsonWebParam;
import com.yanqu.road.logic.bussiness.platform.DeductIngotBussiness;
import com.yanqu.road.logic.bussiness.player.UserBussiness;
import com.yanqu.road.logic.bussiness.recharge.RechargeBussiness;
import com.yanqu.road.logic.config.ChannelConfig;
import com.yanqu.road.server.helper.SignHelper;
import com.yanqu.road.server.manger.AppKeyMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.web.WebServer;
import com.yanqu.road.web.controller.BaseJsonHttpServlet;
import com.yanqu.road.webservice.invoke.GameWebServiceInvoke;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
import java.util.SortedMap;

@WebServlet(urlPatterns = "/deductIngots")
public class DeductIngots extends BaseJsonHttpServlet {

	private static Logger logger = LogManager.getLogger(DeductIngots.class.getName());

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.info("request deductIngots");
		HttpJsonWebParam httpJsonWebParam = super.parseRequest(request);
		JSONObject paramObj = httpJsonWebParam.getParamObj();
		String appid;
		String platformUserId;
		String gameId;
		String childGameId;
		String platformOrderNo;
		String orderNo;
		String money;
		String mallId;
		long userId;
		long ingotCount;
		long time;
		String ext;
		String sign;
		try{
			appid = paramObj.getString("appid");
			platformUserId = paramObj.getString("uid");
			gameId = paramObj.getString("game_id");
			childGameId = paramObj.getString("fx_c_game_id");
			userId = paramObj.getLongValue("actor_id");
			platformOrderNo = paramObj.getString("order_id");
			orderNo = paramObj.getString("order_no");
			money = paramObj.getString("money");
			ingotCount = paramObj.getLongValue("game_coin");
			mallId = paramObj.getString("product_id");
			time = paramObj.getLong("time");
			ext = paramObj.getString("ext");
			sign = paramObj.getString("sign");
		} catch (Exception e) {
			logger.error("deductIngots args error:" + e);
			sendResult(response, 0, "args error");
			return;
		}
		try{
			SortedMap<String, String> paramMap = SignHelper.getParamMap(paramObj);
			if(!SignHelper.checkSign(paramMap, AppKeyMgr.getAndroidAppSecret(), sign)){
				if(ServerListMgr.isCnMergeServer(WebServer.getInstance().getServerId())){
					if(!SignHelper.checkSign(paramMap, ChannelConfig.APP_SECRET_CONFIG, sign)){
						logger.error("deductIngots sign error");
						sendResult(response, 0, "sign error");
						return;
					}
				}else {
					logger.error("deductIngots sign error");
					sendResult(response, 0, "sign error");
					return;
				}
			}
			PlatformDeductIngotsOrder deductIngotsOrder = DeductIngotBussiness.getPlatformDeductIngotsOrder(orderNo);
			if(null != deductIngotsOrder){
				logger.error("deductIngots orderNo already exist,orderNo:{}", orderNo);
				sendResult(response, 0, "orderNo already exist");
				return;
			}
			UserInfo userInfo = UserBussiness.getUserInfoByUserId(userId);
			if (null == userInfo) {
				logger.error("deductIngots user no find,orderNo:{},userId{}", orderNo, userId);
				sendResult(response, 0, "role no find");
				return;
			}
			if (!Objects.equals(userInfo.getPlatformUserId(), platformUserId)) {
				logger.error("deductIngots platformUserId error,orderNo:{},local platformUserId:{}; platformUserId:{}",
						orderNo, userInfo.getPlatformUserId(), platformUserId);
				sendResult(response, 0, "dirty userId");
				return;
			}
			//判断玩家的充值订单存在
//			RechargeOrder rechargeOrder = RechargeBussiness.getRechargeOrder(orderNo);
//			if(null == rechargeOrder){
//				ThirdPartyRechargeOrder thirdPartyRechargeOrder = RechargeBussiness.getThirdPartyRechargeOrder(orderNo);
//				if(null == thirdPartyRechargeOrder){
//					logger.error("deductIngots recharge order no find,orderNo:{}", orderNo);
//					sendResult(response, 0, "recharge order no find");
//					return;
//				}
//			}
			deductIngotsOrder = new PlatformDeductIngotsOrder();
			deductIngotsOrder.setOrderNo(orderNo);
			deductIngotsOrder.setUserId(userId);
			deductIngotsOrder.setIngotCount(ingotCount);
			deductIngotsOrder.setAppid(appid);
			deductIngotsOrder.setPlatformUserId(platformUserId);
			deductIngotsOrder.setGameId(gameId);
			deductIngotsOrder.setChildGameId(childGameId);
			deductIngotsOrder.setPlatformOrderNo(platformOrderNo);
			deductIngotsOrder.setMoney(money);
			deductIngotsOrder.setMallId(mallId);
			deductIngotsOrder.setTime(time);
			deductIngotsOrder.setExt(ext);
			if(!DeductIngotBussiness.addPlatformDeductIngotsOrder(deductIngotsOrder)){
				logger.error("deductIngots fail,add to db fail,orderNo:{},platformUserId:{},userId:{},count:{}", orderNo,
						platformUserId, userId, ingotCount);
				sendResult(response, 0, "unknown error");
				return;
			}
			sendResult(response, 1, "success");
			GameWebServiceInvoke.notifyDeductIngots(orderNo);
		} catch (Exception e) {
			logger.error("deductIngots error:" + e);
			sendResult(response, 0, "other error");
		}
	}
}
